<?php
session_start();

$refPage = "uploader.php";
include '../langincluder.php';

//fetched from the session and SQL
$userName = $_SESSION['userName'];
if( empty($userName) )
{
	$userName = $strings['notLoggedIn'];
	$maxFileSizeKB = 0; // 0 = no restriction
	$userGrantedSpaceMB = 0; // 0 = none, -1 = inlimited
	$userUsedSpaceKB = 0;
	$allowedTypes = "none"; // none || images || all
}
else // load it all
{
	require("../sql/sqlCon.php");
	$q = mysql_query("SELECT uploadMaxFileSizeKB, uploadGrantedSpaceMB, uploadUsedSpaceKB, uploadAllowedTypes FROM $usersExtendedTableName WHERE userId = '".$_SESSION['userId']."'");
	$r = mysql_fetch_array($q); echo mysql_error();
	$maxFileSizeKB = $r['uploadMaxFileSizeKB'];
	$userGrantedSpaceMB = $r['uploadGrantedSpaceMB'];
	$userUsedSpaceKB = $r['uploadUsedSpaceKB'];
	$allowedTypes = $r['uploadAllowedTypes'];
}

calcUsed(); // bellow...

// some configs
$formFileName = 'uploadedfile'; // the name of the form
require 'uploaderConfigs.php';


$uploadStateFlag = 0;	
	
$fileName = "";
if(isset($_FILES[$formFileName]) && !empty($_FILES[$formFileName]['name'])) 
	$uploadStateFlag = fileSaver();

function fileSaver()
{
	global $fileName, $formFileName, $savePath, $maxFileSizeKB;
	global $savePath, $userName;
	global $allowedTypes, $percentageUsed;
	global $userUsedSpaceKB, $uploadsTableName, $usersExtendedTableName, $path;
	global $maxOrigFileName, $maxDescription;
	
	if($percentageUsed > 100) return -5;
	
	$fileSize = $_FILES[$formFileName]['size'];
	if( $maxFileSizeKB != 0 && ( $fileSize > $maxFileSizeKB*1024 || $_FILES[$formFileName]['error'] == 2 || $_FILES[$formFileName]['error'] == 1) ) return -1;
	if( $_FILES[$formFileName]['error'] === UPLOAD_ERR_OK ){} 
	else{ echo "php error - ".$_FILES[$formFileName]['error'].", see <a href='http://php.net/manual/en/features.file-upload.errors.php'>here</a>"; return -2;} 
	
	//$_FILES[$formFileName]['type']	
	if( $allowedTypes == "none" ) return -3;
	$imageInfo = getimagesize ( $_FILES[$formFileName]['tmp_name'] );
	if( empty($imageInfo) && $allowedTypes!='all' ) return -3;
	
	
	$t = getdate();
	$extension = substr($_FILES[$formFileName]['name'], strripos($_FILES[$formFileName]['name'], '.'), strlen($_FILES[$formFileName]['name']));
	// if the file is private, add a nice sha1 in the name so it cant be guessed
	$fileName = "$savePath/".$userName."__".$t['hours'].'-'.$t['minutes'].'-'.$t['seconds'].'__'.$t['mday'].'-'.$t['mon'].'-'.$t['year'].($_POST['fSharing'] == 'priv' ? "-".substr(sha1(rand()), 0, 18) : "").$extension;
	$tempc = $_FILES[$formFileName]['name'];
	if( ! move_uploaded_file($_FILES[$formFileName]['tmp_name'], getcwd()."/".$fileName) ) return -4;
	
	// SQL QUERY !
	$q = mysql_query("SELECT fileId FROM $uploadsTableName ORDER BY fileId DESC LIMIT 1");
	$r = mysql_fetch_array($q);
	$fidn = $r['fileId']+1;
	
	$str = "http://".$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME'];
	$path = substr($str, 0, strrpos($str, "/")+1).$fileName;
	
	
	$mcstate = (bool)get_magic_quotes_gpc();
	$origFileName = substr(($mcstate ? $tempc : mysql_real_escape_string($tempc)), 0, $maxOrigFileName);
	$desc = substr(($mcstate ? $_POST['desc'] : mysql_real_escape_string($_POST['desc'])), 0, $maxDescription);

	
	mysql_query("INSERT INTO $uploadsTableName (fileId, byUserId, filePath, fileSizeKB, uploadedDate, isImg, isPrivate, origFileName, description)
				 VALUES ('$fidn', '".$_SESSION['userId']."', '$path', '".$fileSize/1024 ."', '".date('j/n/Y, H:i')."', '".(bool)(!empty($imageInfo))."', '".($_POST['fSharing'] == 'priv' ? 1 : 0)."', '$origFileName', '$desc')");
	
	$userUsedSpaceKB = $userUsedSpaceKB + (int)($fileSize/1024) ;
	mysql_query("UPDATE $usersExtendedTableName
				 SET uploadUsedSpaceKB = '$userUsedSpaceKB'
				 WHERE userId = '".$_SESSION['userId']."'");
	
	
	if(!empty($imageInfo))//create a thumb image
	{ // [0] width //// [1] height 
		$maxWH = 80;
		if( $imageInfo[0] > $maxWH || $imageInfo[1] > $maxWH )
		{
			include('SimpleImage.php');
			$image = new SimpleImage();
			$image->load($fileName);
			if( $imageInfo[0] > $imageInfo[1] )
				$image->resizeToWidth($maxWH);
			else
				$image->resizeToHeight($maxWH);
			$image->save($fileName."_thumb.jpeg");
		}
	}
	
	calcUsed();
	return 1;
}

function calcUsed()
{
	global $userGrantedSpaceMB, $userUsedSpaceKB, $percentageUsed;
	if( $userGrantedSpaceMB == 0) $percentageUsed = 100;
	else if ( $userGrantedSpaceMB == -1 ) $percentageUsed = 0;
	else $percentageUsed = round($userUsedSpaceKB/1024 / $userGrantedSpaceMB * 100, 2);
}

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1251" >
<title>BytePool</title>

<style type="text/css">
body
{
	font-family : Arial, Helvetica,sans-serif;
	font-size : 12px;
	background-color : #F5F5F5;
}

table.uploadTable
{
	padding:3px;
	border-width: 0px 0px 0px 1px;
	padding: 0px 0px 0px 0px;
	border-style: none none none dotted;
	border-color: gray gray gray #0066FF;
}
table.uploadTable td 
{
	border-width: 1px 1px 1px 1px;
	padding: 6px 3px 2px 3px;
	border-style: none none dotted none;
	border-color: gray gray #0066FF gray;
}
</style>

</head>
<body>


<form enctype="multipart/form-data" action="uploader.php" method="post">
<?php if( $maxFileSizeKB > 0) echo'<input type="hidden" name="MAX_FILE_SIZE" value="'.$maxFileSizeKB*1024 .'" >'; ?>

<table class='uploadTable' width="370">

<tr>
<td><?php echo $strings['userName']; ?></td>
<td align="right"><?php if( empty($userName) ) echo $strings['notLoggedIn'];
										  else echo $userName; ?></td>
</tr>

<tr>
<td><?php echo $strings['storageAllowed']; ?></td>
<td align="right"><?php if( $userGrantedSpaceMB == 0) echo $strings['noSpaceGranted'];
					  else if ( $userGrantedSpaceMB == -1) echo $strings['unlimitedSpaceGranted'];
								else echo $userGrantedSpaceMB." Mb"; ?></td>
</tr>

<tr>
<td><?php echo $strings['storageUsed']; ?></td>
<td align="right"><?php if($userUsedSpaceKB>1024) echo round($userUsedSpaceKB/1024, 2)." Mb (";
											 else echo $userUsedSpaceKB." Kb (";
												  echo $percentageUsed." %)"; ?></td>
</tr>

<tr>
<td><?php echo $strings['maxFileSize']; ?></td>
<td align="right"><?php if( $maxFileSizeKB > 0 ) echo $maxFileSizeKB." Kb"; else echo $strings['unlimitedFileSize']; ?></td>
</tr>

<tr>
<td><?php echo $strings['state']; ?></td>
<td align="right"><?php if($uploadStateFlag >= 0 ) echo "<div style='color:#009900;'>";
						else echo "<div style='color:#aa0000;'>";
						
						if($percentageUsed > 100 ) echo $uploadErrors[1];
						else if($uploadStateFlag > 0) echo $uploadErrors[0]; 
						else echo $uploadErrors[ -$uploadStateFlag+2 ];
						
						echo "</div>";?></td>
</tr>

<?php
echo "
<tr>
<td>".$strings['allowedFiletypes']."</td>
<td align='right'>
";
if( $allowedTypes == "all" ) echo $strings['noRestrictions'];
else if ( $allowedTypes == "none" ) echo $strings['noAllowedTypes'];
else if ( $allowedTypes == "images" ) echo $strings['allowedImages']."<br>";
echo "
</td>
</tr>
";



if( $allowedTypes == "none" )
{
if( !isset($_SESSION['userName']) || empty($_SESSION['userName']) )
echo "
<tr>
<td colspan='2' align='center'>
<div style='font-size:80%; color:#aa0000; border:2px solid #FF0000; padding:2px;'>".$strings['loginToUse']."
</div>
</td>
</tr>";

else echo "
<tr>
<td colspan='2' align='center'>
<div style='font-size:80%; color:#aa0000; border:2px solid #FF0000; padding:2px;'>".$strings['noAllowedTypesNotificaton']."
</div>
</td>
</tr>";
}
else{
if($percentageUsed < 100)
echo "
<tr>
<td>".$strings['fileChoose']."</td>
<td align='right'><input name='$formFileName' type='file'></td>
</tr>

<tr>
<td>".$strings['fileSharing']."</td>
<td align='center'><input name='fSharing' type='radio' value='priv'>".$strings['fileSharingPrivate']."&nbsp;&nbsp;&nbsp;&nbsp;
	".$strings['fileSharingPublic']."<input name='fSharing' type='radio' value='publ' checked></td>
</tr>

<tr>
<td>".$strings['description']."</td>
<td align='right'><textarea name='desc' rows='2' cols='25'></textarea></td>
</tr>

<tr>
<td colspan='2' align='center'>
<div style='font-size:80%; color:#aa0000;'><br>
<input type='submit' value='".$strings['uploadButtonText']."' >
</div>
</td>
</tr>";

else
echo "
<tr>
<td colspan='2' align='center'>
<div style='font-size:80%; color:#aa0000; border:2px solid #FF0000; padding:2px;'>".$strings['fullStorageSpaceNotification']."
</div>
</td>
</tr>
";

if( $uploadStateFlag > 0)
echo "
<tr>
<td colspan='2' style='padding:3px;' align='center'>
".$strings['uploadSuccessfulNotification']."
<a href='$path'> Link </a>
</td>
</tr>
";
}
?>

</table>
</form>

</body>